/* eslint-disable no-async-promise-executor */
const model = require("../models/model")
const { Op } = require("sequelize")

const MyGoodsListRate = model.goodsdetailsRate.MyGoodsListRate
const MyGoodsListReply = model.goodsdetailsReply.MyGoodsListReply

exports.getList = async(ctx) => {
  const { getUserInfo, getGoodsDetail } = require('../models/utils')
  const { page, size, goodsId } = ctx.request.query
  if (!page || !size) {
    ctx.fail('参数错误')
    return
  }
  // 查询回复评论item
  function replyItem(id) {
    return new Promise(async(resolve) => {
      const reply = await MyGoodsListReply.findOne({ where: { parentId: id } })
      if (!reply) {
        resolve(null)
        return
      }
      const userInfo = await getUserInfo({ userId: reply.userId, adminId: reply.adminId })
      resolve({
        ...reply,
        user: userInfo.user,
        admin: userInfo.admin
      })
    })
  }
  function getItem(item) {
    return new Promise(async(resolve) => {
      const userInfo = await getUserInfo({ userId: item.userId, adminId: item.adminId })
      const goods = await getGoodsDetail(item.goodsId)
      const reply = await replyItem(item.id)
      resolve({
        ...item,
        goods,
        reply: reply,
        user: userInfo.user,
        admin: userInfo.admin
      })
    }) 
  }
  // 获取总数据
  function allFn() {
    return new Promise(async(resolve) => {
      const res = await MyGoodsListRate.findAndCountAll({
        order: [
          ['createTime', 'DESC'],
        ],
        where: goodsId ? { goodsId } : {},
        offset: (page - 1) * size,
        limit: parseInt(size)
      })
      if (res.rows.length > 0) {
        let flag = 0
        for(let i = 0; i < res.rows.length; i++) {
          getItem(res.rows[i]).then(data => {
            flag++
            res.rows[i] = data
            if (flag === res.rows.length) { // 异步循环完成
              resolve(res)
            }
          })
        }
      } else {
        resolve(res)
      }
    })
  }
  // let where = {}
  // if (goodsId) {
  //   where = { goodsId: parseInt(goodsId) }
  // }

  // function allFn() {
  //   return new Promise(async(resolve) => {
  //     const rate_res = await MyGoodsListRate.findAndCountAll({
  //       where,
  //       offset: (page-1) * size,
  //       limit: parseInt(size)
  //     })
  //     if (rate_res !== undefined && rate_res.rows.length > 0) {
  //       let parentIdList = [] // 评论列表的id
  //       for (let i = 0; i < rate_res.rows.length; i++) {
  //         parentIdList.push(rate_res.rows[i].id)
  //       }
        
  //       const reply_res = await MyGoodsListReply.findAll({
  //         where: {
  //           parentId: {
  //             [Op.or]: parentIdList // 更精准查找 不浪费资源
  //           }
  //         }
  //       })
  //       if (reply_res) {
  //         for (let i = 0; i < rate_res.rows.length; i++) {
  //           rate_res.rows[i]['children'] = []
  //           for(let j = 0; j < reply_res.length; j++) {
  //             if (rate_res.rows[i].id === reply_res[j].parentId) {
  //               rate_res.rows[i]['children'].push(reply_res[j])
  //             }
  //           }
  //         }
  //         resolve(rate_res)
  //       }
  //     } else {
  //       resolve(rate_res)
  //     }
  //   })
  // }
  const res = await allFn()
  if (res) {
    ctx.success({
      total: res.count, // 总页数
      pageNum: Math.trunc((res.count + (size -1) )/size), // 分页数量
      page: parseInt(page), // 页码
      size: parseInt(size), // 页数
      list: res.rows
    })
  }
}

exports.replyComments = async(ctx) => {
  const { parentId, type, adminId, userId, description } = ctx.request.body
  if (!parentId || !type || !adminId || !userId || !description) {
    ctx.fail('参数错误')
    return
  }
  function allFn() {
    return new Promise(async(resolve) => {
      const reply = await MyGoodsListReply.findOne({ where: { parentId }})
      if (!reply) {
        const res = await MyGoodsListReply.create(ctx.request.body)
        resolve(res)
      } else {
        resolve()
      }
    })
  }
  const res = await allFn()
  if (res) {
    ctx.success('', '回复成功')
  } else {
    ctx.fail('已回复该评价')
  }
}
